package com.mall.pay.services;

import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.order.OrderCoreService;
import com.mall.pay.PayCoreService;
import com.mall.pay.constants.PayResultEnum;
import com.mall.pay.constants.PayReturnCodeEnum;
import com.mall.pay.dal.entitys.Payment;
import com.mall.pay.dal.persistence.PaymentMapper;
import com.mall.pay.dto.PaymentRequest;
import com.mall.pay.dto.alipay.AlipayQueryRetResponse;
import com.mall.pay.dto.alipay.AlipaymentResponse;
import com.mall.user.IUserService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.io.File;
import java.util.List;

@Service
public class PayCoreServiceImpl implements PayCoreService {

    @Autowired
    PayHelper payHelper;

    @Reference(check = false,timeout = 3000)
    OrderCoreService orderCoreService;

    @Autowired
    PaymentMapper paymentMapper;

    /*
         获取支付二维码
     */
    @Override
    public AlipaymentResponse aliPay(PaymentRequest request) {

        AlipaymentResponse alipaymentResponse = new AlipaymentResponse();

        //  1. 向支付宝后台发请求，获取支付二维码
        String fileName = payHelper.test_trade_precreate(request);

        //  2. 如果获取支付二维码失败，直接返回二维码获取失败
        if (fileName == null) {
            alipaymentResponse.setCode(PayReturnCodeEnum.GET_CODE_FALIED.getCode());
            alipaymentResponse.setMsg(PayReturnCodeEnum.GET_CODE_FALIED.getMsg());
            return alipaymentResponse;
        }

        //  3. 如果获取支付二维码成功
        //     a. tb_payment 插入订单对应的一条支付记录(待支付) PAY_PROCESSING("1","支付处理中")
        Payment payment = new Payment();


        payment.setStatus(PayResultEnum.PAY_PROCESSING.getCode());
        payment.setOrderId(request.getTradeNo());
        payment.setProductName(request.getSubject());
        payment.setOrderAmount(request.getOrderFee());
        payment.setPayWay("ali_pay");
        payment.setPayerAmount(request.getOrderFee());
        payment.setPayerUid(request.getUserId());


        paymentMapper.insertNewPaymentInfo(payment);

        //     b. 将获取到的支付二维码返回给前端
        alipaymentResponse.setCode(PayReturnCodeEnum.SUCCESS.getCode());
        alipaymentResponse.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());
        alipaymentResponse.setQrCode(fileName);

        return alipaymentResponse;
    }

    /*
           查询订单的支付结果
     */
    @Override
    public AlipayQueryRetResponse queryAlipayRet(PaymentRequest request) {

        //  根据订单id查询订单支付结果
        boolean success = payHelper.test_trade_query(request);
        AlipayQueryRetResponse response = new AlipayQueryRetResponse();


        // 如果success为null代表订单已经被关闭

        if (success) {
            // 支付成功
            // 1. 修改tb_payment中的对应订单的支付状态，支付成功时间，完成时间 PAY_SUCCESS("2","支付成功")
            paymentMapper.successPayment(request.getTradeNo());
            //orderCoreService.payOrderSuccess()


            //  通过调用订单服务来完成
            // 2. 修改订单状态 ——> 已支付
            // 3. 访问tb_stock扣减锁定库存
            //     a.  根据订单id，查询到所有订单商品条目
            //     b.  遍历每一个订单 商品条目，根据购买的数量，扣减对应商品的锁定库存
            orderCoreService.changeOrderStatus(request.getTradeNo(), true);

            response.setCode(PayReturnCodeEnum.SUCCESS.getCode());
            response.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());
            return response;
        } else {
            // 支付失败 ,由超时自动处理，这里只用返回对应的状态就可以。
            // 1. 修改tb_payment中的对应订单的支付状态，支付成功时间，完成时间  PAY_FAIL("3","支付失败");
//            paymentMapper.failPayment(request.getTradeNo());
//            orderCoreService.changeOrderStatus(request.getTradeNo(), false);
            response.setCode(PayReturnCodeEnum.PAYMENT_PROCESSOR_FAILED.getCode());
            response.setMsg(PayReturnCodeEnum.PAYMENT_PROCESSOR_FAILED.getMsg());
        }

        return response;
    }

    @Override
    public boolean queryPayStatus(String orderId) {
        Example example = new Example(Payment.class);
        example.createCriteria().andEqualTo("orderId", orderId);
        List<Payment> payments = paymentMapper.selectByExample(example);
        // 无此订单的支付表信息,代表着秒杀入口,跳过该层检查
        if (payments.size() == 0) {
            return true;
        }

        return Integer.parseInt(payments.get(0).getStatus()) == 2;
    }

    /**
     * @param orderId: 订单ID
     *                 用来修改支付表中的状态为支付失败
     */
    @Override
    public void changePaymentFailStatus(String orderId) {
        paymentMapper.failPayment(orderId);
    }
}
